<?php
namespace control;

//管理员后台-移库单
use JetBrains\PhpStorm\NoReturn;

class moveStockClass extends adIndexClass
{
	private const title       = '移库单';
	private const page        = 'moveStock';
	private const table       = 'inventory_changes';
	private const tableMx     = 'inventory_changes_detail';
	private const tableRecord = 'inventory_record';
    private const optType     = ['采购收货', '生产领料', '其他出库', '销售退货', '生产退料', '生产入库', '采购退货', '其他入库', '销售发货'];


	/**
	 * 移库
	 *
	 * @return string
	 */
	public function home(): string
	{
	    //移库对象
	    $type = radio(array('name' => 'type', 'value' => ['单据条码','存货条码','仓位条码'], 'checked' => '单据条码'));
	    $codeInput = text(array("name" => "code", "class" => "text left", "id" => "barcode", "title" => L('moveStock.home.code')));
        $checkAll = $this->checkAll("detailForm", "listId");
        $tr[]     = [$checkAll, '{l.moveStock.home.list}', '{l.moveStock.home.materialCode}', '{l.moveStock.home.name}', '{l.moveStock.home.model}', '{l.moveStock.home.unit}', '{l.moveStock.home.num}', '{l.moveStock.home.warehouse}', '{l.moveStock.home.location}', '{l.moveStock.home.inTime}', '{l.moveStock.home.orderNo}', '{l.moveStock.home.businessType}', '{l.moveStock.home.target}', '{l.moveStock.home.materialType}', '{l.moveStock.home.batch}'];
        $transferTable = $this->tableMany(array('tr' => $tr, 'end' => true, 'displayFields' => false));

        //移库记录
        $checkAll = $this->checkAll("detailForm", "recordId");
        $transferRadio = radio(array('name' => 'transferStyle', 'value' => ['仅移库'], 'checked' => '仅移库'));
        $locationInput = "<span style='position: relative'>".text(array('name' => 'location','class'=>'text', 'id' => 'locationCode', 'title' => L('moveStock.home.code'), "blur" => "getLocation")) . "<img onclick=\"layer('{$this->get('cla')}','choiceLocation')\" style='position:absolute;right:10px;top:1px;cursor: pointer;' src='".root."img/control/find.svg?v=2'/></span>";
        $trRecord[]     = [$checkAll, '{l.moveStock.home.list}', '{l.moveStock.home.materialCode}', '{l.moveStock.home.name}', '{l.moveStock.home.model}', '{l.moveStock.home.unit}', '{l.moveStock.home.num}', '{l.moveStock.home.outWarehouseId}', '{l.moveStock.home.outLocation}', '{l.moveStock.home.inWarehouseId}', '{l.moveStock.home.inLocation}', '{l.moveStock.home.materialType}', '{l.moveStock.home.batch}', '{l.moveStock.home.operator}', '{l.moveStock.home.time}'];
        $moveRecordId = array_filter((array)explode(',',$this->get('moveRecordId'))); //移库记录id
        foreach ($moveRecordId as $k => $recordId) {
            $inventory_transfer = query("inventory_transfer", " id = '$recordId' ");
            $material = query('material', "id = '$inventory_transfer[materialId]'");
            $dominate = $this->dominate([
                "box" => ["name" => "recordId", "value" => $recordId],
            ]);
            $list = $k + 1;
            $time = self::formatDate($inventory_transfer['time']);
            $trRecord[] = [$dominate,
                $list,
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                self::lostZero($inventory_transfer['num'],'numPrecision'),
                warehouseClass::getName($inventory_transfer['warehouseId']),
                warehousePositionClass::getName($inventory_transfer['positionId']),
                warehouseClass::getName($inventory_transfer['inWarehouseId']),
                warehousePositionClass::getName($inventory_transfer['inLocationId']),
                $material['typeName'],
                $inventory_transfer['batch'],
                self::findStaff($inventory_transfer['stid']),
                $time
            ];
        }

        $transferRecordTable = $this->tableMany(array('tr' => $trRecord, 'end' => true, 'displayFields' => false));

        //移库记录隐藏域id
        $hidden = hidden(['name'=>'moveRecordId','value'=>$this->get('moveRecordId')]);
        $searchWord = L('moveStock.home.search');
        $moveObjWord = L('moveStock.home.moveObj');
        $addWord = L('moveStock.home.add');
        $moveWord = L('moveStock.home.move');
        $inLocationWord = L('moveStock.home.inLocation');
        $sureWord = L('moveStock.home.sure');
        $moveRecordWord = L('moveStock.home.moveRecord');
        $revokeWord = L('moveStock.home.revoke');
		$data['html'] = <<<EOT
                    <div class="w-kuang">
                    <form name="detailForm">
                        <div class="transfer-box box-one">
                            <div class="operate-div">
                                <p>$type</p>
                                <p>$codeInput<span class="spanButton m-l-5" onclick="getObj(this)">$searchWord</span></p>
                                <p class="searchText" id="choiceText"></p>
                            </div>
                            <p class="m-b-8">$moveObjWord<span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name=detailForm]').serialize())">$addWord</span><span class="smallButton" onclick="removeObj()">$moveWord</span></p>
                            <div id="transfer">$transferTable</div>
                        </div>
                        <div class="transfer-box box-two">
                            <div class="operate-div b-c-w">
                                <p>$transferRadio</p>
                                <p class="location-p"><span class="location-title">$inLocationWord</span> $locationInput <span class="spanButton sure-but" onclick="sub()">$sureWord</span></p>
                                <p class="searchText" id="locationText"></p>
                            </div>
                            <p class="m-b-8">$moveRecordWord<span class="smallButton"  onclick="layer('{$this->get('cla')}', 'operate', {'act': 'revoke'})">$revokeWord</span></p>
                            <div id="transfer_record">
                                $transferRecordTable
                            </div>
                        </div>
                        $hidden
                    </div>
                    </form>
                    <style>
                        .w-kuang{padding: 0 10px;}
                        .transfer-box{
                            width: 49%;
                            float: left;
                        }
                        .box-one{
                            margin-right: 1%;
                        }
                        .operate-div{
                            height: 100px;
                            padding: 22px 1px;
                        }
                        .m-b-8{
                            margin-bottom: 8px;
                        }
                        .b-c-w{
                            background-color: whitesmoke;
                        }
                        .location-p{
                            line-height: 31px;
                            height: 31px;
                        }
                        .location-title{
                            display: inline-block;
                            height: 24px;
                            background-color: white;
                            padding: 2px 4px;
                            line-height: 24px;
                            margin-left: 5px;
                            margin-right: -5px;
                            border: 1px solid #d7d7d7;
                            outline: none;
                        }
                        #locationCode,#barcode{
                            border-radius: 0px!important;
                        }
                        .sure-but{
                            display: inline-block;
                            float: right;
                            margin-right: 20px;
                            border: 1px solid #6aacfb;
                            color: #f8f8f8 !important;
                            background-color: #6aacfb;
                            height: 30px;
                            line-height: 30px;
                        }
                        .searchText{
                            padding: 8px; 
                        }
                        .w-kuang .table_many_shell{
                            min-height: 500px;
                            max-height: 500px;
                        }
                        #transfer_record,#transfer{
                            border: 1px solid #e2e2e2;
                        }
                    </style>
                    <script>
                        $(function() {
                            // 表格固定
                            const obj = $('.tableMany')
                            obj.fixedThead()
                        })
                        /***扫码操作***/
                        $("#barcode").on('keydown',function(event) {
                            if (event.keyCode==13){
                                let code = $(this).val();//条码
                                if (!code){
                                    msg('未找到条码','error')
                                    return '';
                                }
                                getObj(this)
                            }
                        });
                        //查询移库对象
                        function getObj(e){
                            //添加
                            let code = $("#barcode").val()
                            let type = $("input[name='type']:checked").val()
                             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getObj',{code:code,type:type},function(res) {
                                 if (res.warn===2){
                                    $("#transfer tbody").html(res.html);
                                    $("#choiceText").html(res.text)
                                    // 表格固定
                                    //const obj = $('.tableMany')
                                    //obj.fixedThead()
                                  }else{
                                    msg(res.warn,'error');
                                  }
                             },'json')
                        }
                        //查询移仓位置
                        function getLocation(e){
                            //添加
                            let locationCode = $("#locationCode").val()
                             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getLocation',{locationCode:locationCode},function(res) {
                                 $("#locationText").text(res.warn)
                             },'json')
                        }
                        function addRow(){
                            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
                                $("#transfer tbody").append(res.html);
                                // 表格固定
                                //const obj = $('.tableMany')
                                //obj.fixedThead()
                            },'json');
                        }
                        function removeObj(){
                            //移除移库对象
                            $("#transfer").find("input[name='listId[]']:checked").each(function (i,e){
                                $(e).parents('tr').remove();
                            })
                        }
                        //选择仓位
                        function addTarget(){
                            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addTargetEdit', $("form[name='locationForm']").serialize(),function(resp) {
                             if (resp.warn === 2){
                                $('#locationCode').val(resp.barcode)
                                $("#locationText").text(resp.text)
                             }else{
                                 msg(resp.warn);
                             }
                            },'json');
                        }
                        //确认提交
                        function sub(){
                            let tbodyNode = $("[name='detailForm'] .fixed-thead-head tbody")
                            let tbody = tbodyNode.html()
                            tbodyNode.html('')
                            subForm('detailForm','{$this->root}control/adIndex.html?cla=moveStock&fun=editEdit')
                            tbodyNode.html(tbody)
                        }
                    </script>
EOT;
		return $this->tab($data);
	}

    /**
     *添加移库对象
     */
    public function getObj()
    {
        $code = $this->post('code');
        $type = $this->post('type');
        $text = "";
        $where = " 1=1 ";
        $and        = " 
        AND d.coid = '" . self::$coid . "' 
        AND i.state in ('已入库', '已出库', '已复核') 
        and i.classify = 1 
        and (SELECT IFNULL(sum(num), 0) as total FROM `inventory_record` where coid = d.coid and materialId = d.materialId and warehouseId = d.warehouseId and positionId = r.positionId and batch = r.batch) > 0 ";  //只查询入库单,库存大于0的
        // 物料条件
        if($type == '存货条码') {
            $material = query("material"," barcode = '$code' ");
            $where .= " AND d.materialId = '$material[id]'  ";
        }elseif($type == '单据条码'){
            $where .= " and i.orderNo = '$code' ";
        }elseif($type == '仓位条码'){
            $warehouse_position = query("warehouse_position"," barcode = '$code' ");
            $where .= " AND r.positionId = '$warehouse_position[id]' ";
        }
        $like       = [
        ];
        $equal      = [
        ];
        $where      .= search(["like" => $like, "=" => $equal]) . $and;
        $page       = find([
            "table"   => " inventory_changes_detail as d left join inventory_record as r on d.id = r.changesId left join inventory_changes as i on d.orderId = i.id ",
            "field"   => "d.*,i.recordDate as orderDate,i.orderNo,i.type,i.targetId,r.positionId,r.time as inTime,r.batch,r.id as rid,(SELECT IFNULL(sum(num), 0) as total FROM `inventory_record` where coid = d.coid and materialId = d.materialId and warehouseId = d.warehouseId and positionId = r.positionId and batch = r.batch) as inventory",
            "where"   => $where." order by d.`time` DESC "
        ]);
        //获取表头
        $checkAll = $this->checkAll("detailForm", "listId");
        $json['html'] = '';
        //$tr[]     = [$checkAll, '{l.moveStock.home.list}', '{l.moveStock.home.materialCode}', '{l.moveStock.home.name}', '{l.moveStock.home.model}', '{l.moveStock.home.unit}', '{l.moveStock.home.num}', '{l.moveStock.home.warehouse}', '{l.moveStock.home.location}', '{l.moveStock.home.inTime}', '{l.moveStock.home.orderNo}', '{l.moveStock.home.businessType}', '{l.moveStock.home.target}', '{l.moveStock.home.materialType}', '{l.moveStock.home.batch}'];
        //获取记录
        foreach ($page['array'] as $k=>$array) {
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['rid']],
            ];
            $material     = query('material', " id = '$array[materialId]'");
            $target       = query('kehu', " khid = '$array[targetId]' ")['companyName'];
            if (empty($target)) {
                $target = query('supplier', " id = '$array[targetId]' ")['name'];
            }
            $warehouseName = warehouseClass::getName($array['warehouseId']);
            $positionName = warehousePositionClass::getName($array['positionId']);
            //$inventoryNum   = inventoryBalanceClass::inventoryNum($array['materialId'], $array['warehouseId'],$array['positionId'],$array['batch']);
            if($k==0){
                if($type == '存货条码') {
                    $text = $material['name'].'-'.$material['model'].'，'.$material['unit'];
                }elseif($type == '单据条码'){
                    $text = L('moveStock.home.businessType').'：'.$array['type']."&nbsp;&nbsp;".L('moveStock.home.target')."：".$target.'<br/>'.L('moveStock.home.orderTime').'：'.self::formatDate($array['time']);
                }elseif($type == '仓位条码'){
                    $text = $warehouseName.' '.$positionName;
                }
            }
            $json['html']     .= $this->createTr([
                $this->dominate($dominate).hidden(['name'=>'objId[]','value'=>$array['rid']]),
                $k+1,
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                "<input name=\"num[]\" type=\"text\" ".self::digitalFiltering('numPrecision')." class=\"text width100\" value=\"".self::lostZero($array['inventory'],'numPrecision')."\">",
                $warehouseName,
                $positionName,
                self::formatDate($array['inTime']),
                $array['orderNo'],
                $array['type'],
                $target,
                $material['typeName'],
                $array['batch'],
            ]);
        }
        $json['warn'] = 2;
        $json['text'] = $text;
        return json_encode($json, 320);
    }
    /***************以为数组生成一个tr******************/
    public function createTr($array)
    {
        $td = '';
        foreach ($array as $value) {
            $td .= "<td>{$value}</td>";
        }
        $row = "<tr>{$td}</tr>";
        return $row;
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        switch ($act) {
            case 'revoke':
                $act      = 'edit';
                $msg      = L('moveStock.operate.msg');
                $title    = L('moveStock.operate.title');
                $function = 'revoke';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('moveStock.operate.warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤销
     *
     * @return bool|string
     */
    public function revoke()
    {
        $array = $this->post('recordId');
        $moveRecordId = explode(',',$this->post('moveRecordId'));
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('moveStock.revoke.power');
        } elseif (empty($array)) {
            $json['warn'] = L('moveStock.revoke.none');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query('inventory_transfer', " coid = '" . self::$coid . "' AND id = '$id' ");
                $newPositionInventory = query(
                    "inventory_record",
                    " coid = '" . self::$coid . "' and warehouseId = '".$info['inWarehouseId']."' and positionId = '".$info['inLocationId']."' and materialId = '".$info['materialId']."' and batch = '".$info['batch']."' and num < 0 and time > '".$info['time']."' ",
                    'id');  //查询转入的仓位该批次是否已有出库记
                if (!$info['id']) {
                    $warn = L('moveStock.revoke.empty');
                }elseif ($info['isRevoke'] == 1) {
                    $warn = L('moveStock.revoke.repeatOperation');
                }elseif (!empty($newPositionInventory['id'])) {
                    $warn = L('moveStock.revoke.repeat');
                } else {
                    //最后删除基本参数
                    update([
                        "table" => 'inventory_transfer',
                        "field" => ['isRevoke'=>1],
                        "where" => "id = '$id'",
                    ]);

                    $details = find([
                        'table' => 'inventory_record',
                        'field' => 'id,moveId,changesId',
                        'where' => " moveId = '{$id}'",
                    ]);
                    foreach ($details['array'] as $key => $value) {
                        $inventory_changes_detail = query('inventory_changes_detail', " coid = '" . self::$coid . "' AND id = '{$value['changesId']}' ","orderId");
                        delete(array("table" => 'inventory_record', "where" => " id = '{$value['id']}' "));
                        delete(array("table" => 'inventory_changes_detail', "where" => " id = '{$value['changesId']}' "));
                        delete(array("table" => 'inventory_changes', "where" => " id = '{$inventory_changes_detail['orderId']}' "));
                    }
                    //返回
                    $warn = L('moveStock.revoke.success');
                    $x++;
                }
                $key = array_search($id,$moveRecordId);
                if($key !== false)unset($moveRecordId[$key]);
                $text .= str_replace(['{{id}}'], [$info['id']], lang('moveStock.revoke.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('moveStock.revoke.log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('moveStock.revoke.warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&moveRecordId=".implode(',',(array)$moveRecordId);
        }
        return json_encode($json, 320);
    }
    /**
     * 获取仓位
     *
     * @return bool|string
     */
    public function getLocation()
    {
        $locationCode = $this->post('locationCode');
        $info = query('warehouse_position', " coid = '".self::$coid."' and barcode = '" . $locationCode . "' ");
        $warehouse = query("warehouse"," id = '".$info['orderId']."' ");
        if (empty($info['id'])) {
            $json['warn'] = L('moveStock.getLocation.empty');
        } else {
            $json['warn']     = $warehouse['name'].' '.$info['name'];
        }
        return json_encode($json, 320);
    }
    /**
     * @return bool|string
     */
    public function addMx(): string
    {
        $html    =
            text(["name" => "code", "title" => "{l.moveStock.home.materialCode}"]) .
            text(["name" => "name", "title" => "{l.moveStock.home.name}"]) .
            materialClass::typeSelect(name: 'typeId') .
            text(['name' => 'orderDate', 'title' => '{l.moveStock.addMx.orderDate}', 'class' => 'text width200', 'laydate' => ['range' => '~', 'type' => 'date'],]) .
            text(["name" => "orderNo", "title" => "{l.moveStock.home.orderNo}"]) .
            select(["name" => "type", "title" => "{l.moveStock.home.businessType}", 'option' => self::optType]) .
            text(["name" => "targetName", "title" => "{l.moveStock.home.target}"]) .
            text(["name" => "batch", "title" => "{l.moveStock.home.batch}"]) .
            selectMultiple([
                'table' => 'warehouse',
                "title" => '{l.moveStock.home.warehouse}',
                'sqlField' => 'name',
                'sqlId' => 'id',
                'where' => "coid = '" . self::$coid . "' AND state = '启用' ",
                'name' => 'warehouseId'
            ]) .
            text(["name" => "location", "title" => "{l.moveStock.home.location}"])
            . hidden(['name' => 'objId', 'value' => implode(',',(array)$this->post('objId'))]);
        $button  = "<input onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub m-l-5' value='".L('moveStock.addMx.sub')."'>";
        $html    = $this->search($html);
        return $this->layer(["title" => L('moveStock.addMx.add'), "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
    }

    /**
     *添加物料
     */
    public function addMxSearch()
    {
        $objId = $this->post('objId') ? explode(',', $this->post('objId')) : [];
        $where      = " 1=1 and r.id not in ('" . implode("','", $objId) . "')";
        $and        = " 
        AND d.coid = '" . self::$coid . "' 
        AND i.state in ('已入库', '已出库', '已复核') 
        and i.classify = 1 
        and (SELECT IFNULL(sum(num), 0) as total FROM `inventory_record` where coid = d.coid and materialId = d.materialId and warehouseId = d.warehouseId and positionId = r.positionId and batch = r.batch) > 0 ";  //只查询入库单,库存大于0的
        // 物料条件
        $mwhere = search([
            "="    => [
                'typePath' => $this->post('typeId'),
            ],
            "like" => [
                'code' => $this->post('code'),
                'name' => $this->post('name'),
            ],
        ]);
        if ($mwhere) {
            $where .= " AND r.materialId in (SELECT id FROM material WHERE 1=1 {$mwhere}  )  ";
        }
        $like       = [
            'r.warehouseId' => $this->post('warehouseId'),
            'r.batch' => $this->post('batch'),
        ];
        $equal      = [
            'i.orderNo' => $this->post('orderNo'),
            'i.type'    => $this->post('type'),
        ];
        if ($this->post('targetName')) {
            $where .= " AND i.targetId IN ( IF(i.classify=1, (SELECT id FROM supplier WHERE coid = '" . self::$coid . "' AND name LIKE '%{$this->post('targetName')}%'), (SELECT khid FROM kehu WHERE coid = '" . self::$coid . "' AND companyName LIKE '%{$this->post('targetName')}%') ) )";
        }
        if ($this->post('location')) {
            $where .= " AND r.positionId in (select id from warehouse_position where name like '%".$this->post('location')."%') ";
        }
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'i.time');
        }
        $where      .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "inventory_changes_detail as d left join inventory_record as r on d.id = r.changesId left join inventory_changes as i on d.orderId = i.id ",
            "field"   => "d.*,i.time as orderDate,i.orderNo,i.type,i.targetId,r.positionId,r.time as inTime,r.batch,r.id as rid,(SELECT IFNULL(sum(num), 0) as total FROM `inventory_record` where coid = d.coid and materialId = d.materialId and warehouseId = d.warehouseId and positionId = r.positionId and batch = r.batch) as inventory",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => " d.`time` DESC ",
        ]);
        $json['sql'] = $page['sql'];
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll,  '{l.moveStock.addMxSearch.date}', '{l.moveStock.home.orderNo}', '{l.moveStock.home.businessType}', '{l.moveStock.home.target}','{l.moveStock.home.materialCode}', '{l.moveStock.home.name}', '{l.moveStock.home.materialType}', '{l.moveStock.home.model}', '{l.moveStock.home.unit}','{l.moveStock.home.batch}','{l.moveStock.home.num}','{l.moveStock.home.warehouse}','{l.moveStock.home.location}'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => ["name" => "mxId", "value" => $array['rid']],
            ];
            $material     = query('material', " id = '$array[materialId]'");
            $target       = query('kehu', " khid = '$array[targetId]' ")['companyName'];
            if (empty($target)) {
                $target = query('supplier', " id = '$array[targetId]' ")['name'];
            }
            //$inventoryNum   = inventoryBalanceClass::inventoryNum($array['materialId'], $array['warehouseId'],$array['positionId'],$array['batch']);
            $tr[]     = [
                $this->dominate($dominate),
                self::formatDate($array['orderDate']),
                $array['orderNo'],
                $array['type'],
                $target,
                $material['code'],
                $material['name'],
                $material['typeName'],
                $material['model'],
                $material['unit'],
                $array['batch'],
                self::lostZero($array['inventory'],'numPrecision'),
                warehouseClass::getName($array['warehouseId']),
                warehousePositionClass::getName($array['positionId']),
            ];
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('moveStock.addMxEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('moveStock.addMxEdit.noChoice');
        } else {
            $json['html'] = '';
            foreach ($mxIdArr as $k=>$mxId) {
                $tableRecord  = query(self::tableRecord, "id = '$mxId'");
                $inventory_detail = query("inventory_detail"," id = '".$tableRecord['inventoryMxId']."' ");
                $inventory = query("inventory"," id = '".$inventory_detail['orderId']."' ");
                $material     = query('material', "id = '$tableRecord[materialId]'");
                $warehouseName    = warehouseClass::getName($tableRecord['warehouseId']);
                $positionName    = warehousePositionClass::getName($tableRecord['positionId']);
                $target       = query('kehu', " khid = '$inventory[targetId]' ")['companyName'];
                if (empty($target)) {
                    $target = query('supplier', " id = '$inventory[targetId]' ")['name'];
                }
                $inventoryNum   = inventoryBalanceClass::inventoryNum($tableRecord['materialId'], $tableRecord['warehouseId'],$tableRecord['positionId'],$tableRecord['batch']);
                $dominate = $this->dominate([
                    "box" => ["name" => "listId", "value" => $mxId],
                ]);
                $list = $k+1;
                $time = self::formatDate($tableRecord['time']);
                $numFiltering = self::digitalFiltering('numPrecision');
                $inventoryNum = self::lostZero($inventoryNum,'numPrecision');
                $json['html'] .= <<<efo
                <tr onclick="tableManyClick(this)">
                    <td>$dominate<input name="objId[]" type="hidden" value="$mxId"></td>
                    <td>{$list}</td>
                    <td>{$material['code']}</td>
                    <td>{$material['name']}</td>
                    <td>{$material['model']}</td>
                    <td>{$material['unit']}</td>
                    <td><input name="num[]" type="text" {$numFiltering} class="text width100" value="{$inventoryNum}"></td>
                    <td>{$warehouseName}</td>
                    <td>{$positionName}</td>
                    <td>{$time}</td>
                    <td>{$inventory['orderNo']}</td>
                    <td>{$inventory['type']}</td>
                    <td>$target</td>
                    <td>{$material['typeName']}</td>
                    <td>{$tableRecord['batch']}</td>
                </tr>
efo;
            }
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
    public function editEdit()
    {
        $objIdArr          = $this->post('objId') ?: [];
        $numArr           = $this->post('num');

        $location        = $this->post('location');
        $warehouse_position = query("warehouse_position"," coid = '".self::$coid."' and barcode = '$location' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('moveStock.editEdit.power');
        } elseif (static::is_null_array($objIdArr)) {
            $json['warn'] = L('moveStock.editEdit.noChoice');
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = L('moveStock.editEdit.emptyNum');
        } elseif (static::isNull($location)) {
            $json['warn'] = L('moveStock.editEdit.noLocation');
        } elseif (empty($warehouse_position['id'])) {
            $json['warn'] = L('moveStock.editEdit.codeError');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            $json['warn'] = L('moveStock.editEdit.success');
            $ids = [];
            //插入移库记录
            foreach ($objIdArr as $k => $nid) {
                $obj          = query(self::tableRecord, "id = '$nid'");
                $material     = query('material', "id = '$obj[materialId]'");
                $outPosition     = query('warehouse_position', "id = '$obj[positionId]'");
                $inventoryNum   = inventoryBalanceClass::inventoryNum($obj['materialId'], $obj['warehouseId'],$obj['positionId'],$obj['batch']);
                $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                if($numArr[$k] > $inventoryNum) {
                    $warn = str_replace(['{{materialName}}','{{location}}','{{batch}}'], [$material['name'],$outPosition['name'],$obj['batch']], L('moveStock.editEdit.insufficientInventory'));
                }elseif($obj['positionId'] == $warehouse_position['id']){
                    $warn = str_replace(['{{materialName}}','{{location}}','{{batch}}'], [$material['name'],$outPosition['name'],$obj['batch']], L('moveStock.editEdit.exists'));
                }else {
                    $id = self::getId();
                    //新增
                    $warn = static::insert([
                        "table" => 'inventory_transfer',
                        "field" => [
                            'id' => $id,
                            'coid' => self::$coid,
                            'warehouseId' => $obj['warehouseId'],
                            'positionId' => $obj['positionId'],
                            'materialId' => $obj['materialId'],
                            'batch' => $obj['batch'],
                            'num' => $numArr[$k],  //移库数量
                            'inWarehouseId' => $warehouse_position['orderId'],
                            'inLocationId' => $warehouse_position['id'],
                            'inventoryId' => $obj['inventoryId'],
                            'inventoryMxId' => $obj['inventoryMxId'],
                            'stid' => $this->control['stid'],
                        ],
                    ]);
                    if($warn == '新增成功'){
                        $recordOutId = self::getNo();
                        //批次出库
                        insert([
                            'table' => self::tableRecord,
                            'field' => [
                                'id' => $recordOutId,
                                'coid' => self::$coid,
                                'warehouseId' => $obj['warehouseId'],
                                'positionId' => $obj['positionId'],
                                'materialId' => $obj['materialId'],
                                'batch' => $obj['batch'],
                                'num' => -1 * $numArr[$k],
                                'inventoryId' => $obj['inventoryId'],
                                'inventoryMxId' => $obj['inventoryMxId'],
                                'moveId' => $id,
                            ],
                        ]);
                        if(!empty($obj['positionId']))
                        {
                            //判断库存是否用完，去掉入库id
                            inventoryBalanceClass::recordStockToLocation('',['materialId'=>$obj['materialId'],'warehouseId'=>$obj['warehouseId'],'positionId'=>$obj['positionId'],'batch'=>$obj['batch']]);
                        }
                        //批次入库
                        $recordInId = self::getNo();
                        insert([
                            'table' => self::tableRecord,
                            'field' => [
                                'id' => $recordInId,
                                'coid' => self::$coid,
                                'warehouseId' => $warehouse_position['orderId'],
                                'positionId' => $warehouse_position['id'],
                                'materialId' => $obj['materialId'],
                                'batch' => $obj['batch'],
                                'num' => $numArr[$k],
                                'inventoryId' => $obj['inventoryId'],
                                'inventoryMxId' => $obj['inventoryMxId'],
                                'moveId' => $id,
                                'time' => $obj['time'],
                            ],
                        ]);
                        if(!empty($warehouse_position['id']))
                        {
                            //插入入库id到仓位
                            inventoryBalanceClass::recordStockToLocation($recordInId,['positionId'=>$warehouse_position['id']]);
                        }
                    }
                    $ids[] = $id;
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $isPass       = false;
                    $json['warn'] = $warn;
                    break;
                }
                // 补出入库记录
                inventoryBalanceClass::otherToinventory('inventory_transfer', $ids);
            }
            if (in_array($json['warn'], ["操作成功"]) && $isPass) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{ids}}'], [$this->control['name'],$type,implode('，',$ids)], L('moveStock.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = L('moveStock.editEdit.success');
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&moveRecordId=" . implode(',',$ids);
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     *选择仓位
     *
     * @return bool|string
     */
    public function choiceLocation(): bool|string
    {
        $html   =
            text(array("name" => "orderNo", "title" => "{l.moveStock.choiceLocation.orderNo}")) .
            text(array("name" => "wName", "title" => "{l.moveStock.choiceLocation.wName}")) .
            selectMultiple(array("name" => "typeId", "title" => "{l.moveStock.choiceLocation.typeId}",'table'=>'warehouse_type','where'=>"coid = '".self::$coid."' order by list asc",'sqlId'=>'id','sqlField'=>"name")) .
            text(array("name" => "code", "title" => "{l.moveStock.choiceLocation.code}")) .
            text(array("name" => "name", "title" => "{l.moveStock.choiceLocation.name}"));
        $button = "<input style='margin-left: 5px' onclick=\"addTarget();$('#" . self::page . "ChoiceLocation').hide()\" type='button' class='searchSub' value='".L('moveStock.choiceLocation.sub')."'>";
        $html   = $this->search($html);
        return $this->layer(["title" => L('moveStock.choiceLocation.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
    }

    /**
     *选择仓位
     */
    public function choiceLocationSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),
            "b.name" => $this->post('wName'),
            "b.typeId" => $this->post('typeId'),
            "a.name" => $this->post('name'),
            "a.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.state" => '启用',//状态
            "a.coid"=>self::$coid
        );
        $where = search(["like" => $like, "=" => $equal]);
        $page  = $this->page(array(
            "table" => 'warehouse_position as a join warehouse as b on a.orderId = b.id',
            'field'=>"a.*,b.orderNo,b.name as aName,b.typeId",
            "where" => $where,
            "order" =>"a.code",
            'pageNum' => 8
        ));
        //获取表头
        $tr[] = array("", "{l.moveStock.choiceLocation.orderNo}", "{l.moveStock.choiceLocation.wName}", "{l.moveStock.choiceLocation.typeId}", '{l.moveStock.choiceLocation.code}', '{l.moveStock.choiceLocation.name}', '{l.moveStock.choiceLocation.barcode}', '{l.moveStock.choiceLocation.text}', '{l.moveStock.choiceLocation.updateTime}');
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[]         = array(
                "<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
                $array['orderNo'],
                $array['aName'],
                warehouseClass::getTypeName($array['typeId']),
                $array['code'],
                $array['name'],
                $array['barcode'],
                $array['text'],
                $array['updateTime'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='locationForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addTargetEdit(): bool|string
    {
        $targetId = $this->post('mxId');
        $target = query('warehouse_position', "id = '$targetId' ");
        $text = '';
        if ($target['id']) {
            $warehouse = query("warehouse"," id = '".$target['orderId']."' ");
            $text = $warehouse['name'].' '.$target['name'];
        }
        $json = [
            'warn' => 2,
            'barcode'=>$target['barcode'],
            'id'=>$target['id'],
            'text'=>$text,
        ];
        return json_encode($json, 320);
    }
}
